//Cracking the coding interview (5th), 1_5
// Implementat a method to perform basic string compression using the counts of repeated characters. For example, the string aabccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

#include<iostream>
#include<string>
#include<sstream>
#include<cstdio>
using namespace std;

int compress_str(string& input, string& output)
{
	size_t i = 0;
        char flag;
        output.clear();

	while(i < input.size()) {
		size_t num = 1;
                stringstream ss;
		flag = input[i++];
		output.push_back(flag);
		while(input[i] == flag) {
			i++;
			num++;
		}
                ss<<num;
		output.append(ss.str());
	}

        if (output.size() >= input.size())
          output = input;
	return 0;
}

int main(int argc, char *argv[])
{
  string str1("aabcccccaaa");
  string str2("abca");
  string str3, str4; 
  compress_str(str1, str3);
  compress_str(str2, str4);
  cout<<str3<<endl;
  cout<<str4<<endl;
  return 0;
}
